package com.bm.specialvehiclefordispatcher.Tools;

import java.io.File;

import android.annotation.SuppressLint;
import android.app.DownloadManager;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Environment;
import android.os.SystemClock;
import android.widget.Toast;

public class UpdateVersionBroadCast extends BroadcastReceiver {

	private DownloadManager manager;
	Context context;

	public UpdateVersionBroadCast(Context context) {
		this.context = context;
	}

	@Override
	public void onReceive(Context context, Intent intent) {
		this.context = context;
		manager = (DownloadManager) context
				.getSystemService(Context.DOWNLOAD_SERVICE);
		queryDownloadStatus(context);

	}

	public static boolean install(Context context, String filePath) {
		Intent i = new Intent(Intent.ACTION_VIEW);
		File file = new File(filePath);
		if (file != null && file.length() > 0 && file.exists() && file.isFile()) {
			i.setDataAndType(Uri.parse("file://" + filePath),
					"application/vnd.android.package-archive");
			i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
			context.startActivity(i);
			return true;
		}
		return false;
	}

	@SuppressLint("NewApi")
	private void queryDownloadStatus(Context context) {
		DownloadManager.Query query = new DownloadManager.Query();
		Cursor c = manager.query(query);
		if (c.moveToFirst()) {
			int status = c.getInt(c
					.getColumnIndex(DownloadManager.COLUMN_STATUS));
			switch (status) {
			case DownloadManager.STATUS_PAUSED:
			case DownloadManager.STATUS_PENDING:
			case DownloadManager.STATUS_RUNNING:
				// 正在下载，不做任何事情
				break;
			case DownloadManager.STATUS_SUCCESSFUL:
				// 完成
				Toast.makeText(context.getApplicationContext(), "新版本下载成功",
						Toast.LENGTH_SHORT).show();
				SystemClock.sleep(1 * 1000);
				String apkFilePath = Environment.getExternalStorageDirectory()
						+ "/Specialvehiclefordispatcher/download/" + "Specialvehiclefordispatcher.apk";
				install(context, apkFilePath);
				break;
			case DownloadManager.STATUS_FAILED:
				// 清除已下载的内容，重新下载
				break;
			}
		}
	}

}
